package me.ivps.android.weibo.ui.main;

import java.lang.reflect.Field;
import java.nio.charset.Charset;

import me.ivps.android.weibo.support.asyncdrawable.TimeLineBitmapDownloader;
import me.ivps.android.weibo.support.error.WeiboException;
import me.ivps.android.weibo.support.settinghelper.SettingUtility;
import me.ivps.android.weibo.support.utils.GlobalContext;
import android.content.Intent;
import android.nfc.NdefMessage;
import android.nfc.NdefRecord;
import android.nfc.NfcAdapter;
import android.nfc.NfcEvent;
import android.os.Bundle;
import android.view.ViewConfiguration;
import android.widget.Toast;

import com.slidingmenu.lib.app.SlidingFragmentActivity;

/**
 * 微博时间线界面父 Activity
 * 
 * User: qii Date: 13-1-22
 */
public class MainTimeLineParentActivity extends SlidingFragmentActivity {
    
    private int theme = 0;
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        // 设置主题
        theme = (savedInstanceState == null) ? SettingUtility.getAppTheme()
                : savedInstanceState.getInt("theme");
        setTheme(theme);
        
        super.onCreate(savedInstanceState);
        
        forceShowActionBarOverflowMenu();
        
        initNFC();
        
        GlobalContext.getInstance().setActivity(this);
        
        // 重置或生成图片下载单例
        TimeLineBitmapDownloader.refreshThemePictureBackground();
    }
    
    @Override
    protected void onResume() {
        super.onResume();
        
        // 设置当前运行的 Activity
        GlobalContext.getInstance().setCurrentRunningActivity(this);
        
        if (theme != SettingUtility.getAppTheme()) {
            reload();
        }
    }
    
    @Override
    protected void onPause() {
        super.onPause();
        
        // 若当前运行的 Activity 指向本 Activity, 则在此置空
        if (GlobalContext.getInstance().getCurrentRunningActivity() == this) {
            GlobalContext.getInstance().setCurrentRunningActivity(null);
        }
    }
    
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        // 保存当前所选主题
        outState.putInt("theme", theme);
    }
    
    /**
     * 强制显示"更多"菜单
     */
    private void forceShowActionBarOverflowMenu() {
        try {
            ViewConfiguration config = ViewConfiguration.get(this);
            // 菜单键
            Field menuKeyField = ViewConfiguration.class
                    .getDeclaredField("sHasPermanentMenuKey");
            // 设置为不拥有菜单键
            if (menuKeyField != null) {
                menuKeyField.setAccessible(true);
                menuKeyField.setBoolean(config, false);
            }
        }
        catch (Exception ignored) {
            
        }
    }
    
    /**
     * 初始化 NFC
     */
    private void initNFC() {
        NfcAdapter mNfcAdapter = NfcAdapter.getDefaultAdapter(this);
        if (mNfcAdapter == null) {
            return;
        }
        
        mNfcAdapter.setNdefPushMessageCallback(
                new NfcAdapter.CreateNdefMessageCallback() {
                    
                    @Override
                    public NdefMessage createNdefMessage(NfcEvent event) {
                        // 当前账户名
                        String text = (GlobalContext.getInstance()
                                .getCurrentAccountName());
                        NdefMessage msg = new NdefMessage(
                                new NdefRecord[] {
                                        createMimeRecord(
                                                "application/org.qii.weiciyuan.beam",
                                                text.getBytes()),
                                        NdefRecord
                                                .createApplicationRecord(getPackageName()) });
                        return msg;
                    }
                }, this);
        
    }
    
    /**
     * 创建 NFC Record 记录
     * 
     * @param mimeType
     * @param payload
     * @return
     */
    private NdefRecord createMimeRecord(String mimeType, byte[] payload) {
        byte[] mimeBytes = mimeType.getBytes(Charset.forName("US-ASCII"));
        NdefRecord mimeRecord = new NdefRecord(NdefRecord.TNF_MIME_MEDIA,
                mimeBytes, new byte[0], payload);
        return mimeRecord;
    }
    
    /**
     * 重新加载应用
     */
    public void reload() {
        Intent intent = getIntent();
        overridePendingTransition(0, 0);
        intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
        finish();
        
        overridePendingTransition(0, 0);
        startActivity(intent);
    }
    
    /**
     * 处理异常
     * 
     * @param e
     */
    protected void dealWithException(WeiboException e) {
        Toast.makeText(this, e.getError(), Toast.LENGTH_SHORT).show();
    }
}
